import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'
import AppLayout from '@/layout/AppLayout.vue'
import projectRouter from './modules/project'
import userRouter from './modules/user'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { useAuthStore } from '@/store'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: AppLayout,
    // 只有经过身份验证的用户才能跳转路由
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/home/index.vue')
      },
      projectRouter,
      userRouter
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(), // 路由模式
  routes // 路由规则
})

router.beforeEach((to, from) => {
  nprogress.start() // 开始加载进度条
  const authStore = useAuthStore() // 在这里调用 useAuthStore
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath }
    }
  }
})

router.afterEach((to, from) => {
  nprogress.done() // 加载进度条结束
})

export default router
